package com.ruoyi.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.StringUtils;
import com.ruoyi.constant.ErrorCode;
import com.ruoyi.entity.PrivilegeUser;
import com.ruoyi.mapper.PrivilegeUserMapper;
import com.ruoyi.response.HttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class HandlerOption implements HandlerInterceptor {

    @Resource
    PrivilegeUserMapper privilegeUserMapper;

    //请求执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        String AppId = request.getHeader("APP-ID");
        String AppKey = request.getHeader("APP-KEY");
        //1：校验用户鉴权参数
        if(StringUtils.isEmpty(AppId)){
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print( HttpResponse.error(ErrorCode.PreconditionFailed,"请求头中未包含APP-ID"));
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
        if(StringUtils.isEmpty(AppKey)){
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print( HttpResponse.error(ErrorCode.PreconditionFailed,"请求头中未包含APP-KEY"));
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
        //2:校验app-Id与app-Key是否正确
        QueryWrapper<PrivilegeUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PrivilegeUser::getAppId,AppId)
                .eq(PrivilegeUser::getAppKey,AppKey);
        PrivilegeUser privilegeUser = privilegeUserMapper.selectOne(queryWrapper);
        if(privilegeUser==null){
            try(PrintWriter printWriter = response.getWriter()){
                printWriter.print( HttpResponse.error(ErrorCode.PreconditionFailed,"权限校验失败！请检查您的输入..."));
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }



    //请求执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在结束之前
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
